/**
 * 卖家管理系统 - 商品管理页面逻辑
 * 功能：编辑商品描述、查看商品购买量
 */

class SellerDashboard {
    constructor() {
        this.currentUser = null;
        this.purchaseChart = null;
        this.init();
    }

    init() {
        this.checkAuth();
        this.bindEvents();
        this.loadDashboardData();
    }

    // 检查用户认证状态
    checkAuth() {
        const user = JSON.parse(localStorage.getItem('currentUser'));
        console.log('当前用户:', user);
        
        if (!user || user.user_type !== 'Seller') {
            console.log('用户未登录或不是卖家，跳转到首页');
            window.location.href = 'index.html';
            return;
        }
        this.currentUser = user;
        document.getElementById('userName').textContent = user.username;
        console.log('卖家认证成功:', user.username);
    }

    // 绑定事件
    bindEvents() {
        // 用户菜单
        const userMenuBtn = document.getElementById('userMenuBtn');
        const userDropdown = document.getElementById('userDropdown');
        
        userMenuBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            userDropdown.classList.toggle('show');
        });

        document.addEventListener('click', () => {
            userDropdown.classList.remove('show');
        });

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            this.logout();
        });

        // 编辑商品模态框事件
        const editProductModal = document.getElementById('editProductModal');
        const closeEditProductModal = document.getElementById('closeEditProductModal');
        const cancelEditProduct = document.getElementById('cancelEditProduct');
        const editProductForm = document.getElementById('editProductForm');

        closeEditProductModal.addEventListener('click', () => {
            this.hideEditProductModal();
        });

        cancelEditProduct.addEventListener('click', () => {
            this.hideEditProductModal();
        });

        editProductForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.updateProductDescription();
        });

        // 点击模态框外部关闭
        editProductModal.addEventListener('click', (e) => {
            if (e.target === editProductModal) {
                this.hideEditProductModal();
            }
        });
    }

    // 加载仪表盘数据
    async loadDashboardData() {
        try {
            this.showLoading();
            
            // 加载商品列表
            await this.loadProducts();
            
            // 加载统计数据
            await this.loadStats();
            
            // 加载购买趋势图表
            await this.loadPurchaseChart();
            
        } catch (error) {
            console.error('加载仪表盘数据失败:', error);
            this.showToast('加载数据失败', 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 加载统计数据
    async loadStats() {
        try {
            console.log('开始加载统计数据，用户名:', this.currentUser.username);
            const res = await api.getSellerProducts(this.currentUser.username);
            console.log('统计数据响应:', res);
            
            if (!res.success) {
                console.error('获取统计数据失败:', res.error);
                throw new Error(res.error || '获取商品失败');
            }
            
            const products = res.data.products || [];
            
            // 计算总销量
            let totalSales = 0;
            for (const product of products) {
                try {
                    const salesRes = await api.getProductSales(product.id);
                    if (salesRes.success) {
                        totalSales += salesRes.data.total_quantity || 0;
                    }
                } catch (error) {
                    console.warn(`获取商品 ${product.id} 购买量失败:`, error);
                }
            }
            
            document.getElementById('totalProducts').textContent = products.length;
            document.getElementById('totalSales').textContent = totalSales;

        } catch (error) {
            console.error('加载统计数据失败:', error);
            this.showToast('加载统计数据失败: ' + error.message, 'error');
        }
    }

    // 加载购买趋势图表
    async loadPurchaseChart() {
        try {
            console.log('开始加载购买统计数据...');
            const res = await api.request('/api/seller/purchase-statistics');
            
            if (!res.success) {
                console.error('获取购买统计失败:', res.error);
                return;
            }
            
            const statistics = res.data.statistics || [];
            
            if (statistics.length === 0) {
                document.getElementById('purchaseChart').parentElement.innerHTML = '<p style="text-align: center; color: #999; padding: 40px;">暂无购买数据</p>';
                return;
            }
            
            // 准备图表数据
            const labels = statistics.map(s => `${s.category} (${s.quantity})`);
            const quantities = statistics.map(s => s.quantity);
            
            // 颜色数组
            const colors = [
                '#FF6B35', '#F7931E', '#4ECDC4', '#45B7D1', 
                '#96CEB4', '#FFEAA7', '#DDA15E', '#BC6C25',
                '#A8DADC', '#457B9D'
            ];
            
            // 销毁旧图表
            if (this.purchaseChart) {
                this.purchaseChart.destroy();
            }
            
            // 创建饼状图
            const ctx = document.getElementById('purchaseChart').getContext('2d');
            this.purchaseChart = new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: quantities,
                        backgroundColor: colors.slice(0, quantities.length),
                        borderColor: '#fff',
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                padding: 15,
                                font: {
                                    size: 14
                                },
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value}件 (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
            
            console.log('购买趋势图表加载完成');
            
        } catch (error) {
            console.error('加载购买趋势图表失败:', error);
            this.showToast('加载购买趋势图表失败', 'error');
        }
    }

    // 加载商品列表
    async loadProducts() {
        try {
            const productsGrid = document.getElementById('productsGrid');
            console.log('开始加载商品列表，用户名:', this.currentUser.username);
            
            const res = await api.getSellerProducts(this.currentUser.username);
            console.log('获取商品列表响应:', res);
            
            if (!res.success) {
                console.error('获取商品失败:', res.error);
                throw new Error(res.error || '获取商品失败');
            }
            
            const products = res.data.products || [];
            console.log('商品数量:', products.length);

            if (products.length === 0) {
                productsGrid.innerHTML = `
                    <div class="no-data">
                        <i class="fas fa-box"></i>
                        <p>暂无商品</p>
                    </div>
                `;
                return;
            }

            // 加载每个商品的购买量
            console.log('开始加载购买量数据...');
            const productsWithSales = await Promise.all(
                products.map(async (product) => {
                    try {
                        const salesRes = await api.getProductSales(product.id);
                        const salesCount = salesRes.success ? (salesRes.data.total_quantity || 0) : 0;
                        return { ...product, salesCount };
                    } catch (error) {
                        console.warn(`获取商品 ${product.id} 购买量失败:`, error);
                        return { ...product, salesCount: 0 };
                    }
                })
            );
            console.log('购买量数据加载完成');

            productsGrid.innerHTML = productsWithSales.map(product => `
                <div class="product-card">
                    <div class="product-image">
                        <img src="${product.image || 'https://via.placeholder.com/200x150?text=商品'}" alt="${product.name}">
                    </div>
                    <div class="product-info">
                        <h3>${product.name}</h3>
                        <p class="product-price">¥${Number(product.price).toFixed(2)}</p>
                        <p class="product-stock">购买量: ${product.salesCount}</p>
                        ${product.description ? `<p class="product-description" title="${product.description}">${product.description.length > 50 ? product.description.substring(0, 50) + '...' : product.description}</p>` : '<p class="product-description text-muted">暂无描述</p>'}
                        <div class="product-actions">
                            <button class="btn btn-sm btn-primary edit-product-btn" data-product-id="${product.id}">
                                <i class="fas fa-edit"></i>
                                编辑描述
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');

            // 绑定编辑按钮的点击事件（使用事件委托）
            productsGrid.querySelectorAll('.edit-product-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    const productId = e.currentTarget.getAttribute('data-product-id');
                    console.log('编辑按钮被点击，商品ID:', productId);
                    this.editProduct(productId);
                });
            });

        } catch (error) {
            console.error('加载商品列表失败:', error);
            this.showToast('加载商品列表失败: ' + error.message, 'error');
        }
    }

    // 编辑商品
    async editProduct(productId) {
        try {
            console.log('开始编辑商品，商品ID:', productId);
            this.showLoading();
            
            // 获取商品详情
            console.log('获取商品详情...');
            const res = await api.getProductDetail(productId);
            console.log('商品详情响应:', res);
            if (!res.success) throw new Error(res.error || '获取商品失败');
            
            const product = res.data;
            console.log('商品数据:', product);
            
            // 获取购买量
            console.log('获取购买量...');
            const salesRes = await api.getProductSales(productId);
            const salesCount = salesRes.success ? (salesRes.data.total_quantity || 0) : 0;
            console.log('购买量:', salesCount);
            
            // 填充表单数据
            document.getElementById('editProductId').value = product.id;
            document.getElementById('editProductName').value = product.name || '';
            document.getElementById('editProductDescription').value = product.description || '';
            document.getElementById('productSalesCount').textContent = salesCount;
            
            // 显示编辑模态框
            console.log('显示编辑模态框...');
            this.showEditProductModal();
            console.log('模态框显示完成');
            
        } catch (error) {
            console.error('加载商品数据失败:', error);
            this.showToast('加载商品数据失败: ' + error.message, 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 显示编辑商品模态框
    showEditProductModal() {
        const modal = document.getElementById('editProductModal');
        if (!modal) {
            console.error('找不到编辑模态框元素');
            return;
        }
        console.log('添加show类到模态框');
        modal.classList.add('show');
        document.body.style.overflow = 'hidden';
        console.log('模态框类列表:', modal.classList.toString());
    }

    // 隐藏编辑商品模态框
    hideEditProductModal() {
        document.getElementById('editProductModal').classList.remove('show');
        document.body.style.overflow = '';
        document.getElementById('editProductForm').reset();
    }

    // 更新商品描述
    async updateProductDescription() {
        try {
            const productId = document.getElementById('editProductId').value;
            const description = document.getElementById('editProductDescription').value.trim();
            
            if (!description) {
                this.showToast('商品描述不能为空', 'error');
                return;
            }

            this.showLoading();

            const payload = {
                description: description
            };

            const res = await api.updateProductDescription(productId, payload);
            if (!res.success) throw new Error(res.error || '更新失败');

            this.showToast('商品描述更新成功！', 'success');
            this.hideEditProductModal();
            this.loadProducts(); // 重新加载商品列表
            this.loadStats(); // 重新加载统计数据

        } catch (error) {
            console.error('更新商品描述失败:', error);
            this.showToast('更新商品描述失败: ' + error.message, 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 退出登录
    logout() {
        localStorage.removeItem('currentUser');
        window.location.href = 'index.html';
    }

    // 显示加载状态
    showLoading() {
        document.getElementById('loading').classList.add('show');
    }

    // 隐藏加载状态
    hideLoading() {
        document.getElementById('loading').classList.remove('show');
    }

    // 显示消息提示
    showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = `toast toast-${type} show`;
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
}

// 初始化卖家仪表盘
const sellerDashboard = new SellerDashboard();
